<template>
  <div class="app-container">
    <div v-if="workflowConfigs">
      <Workflow
        :active-state="activeState"
        :workflow-configs="workflowConfigs"
        :model-name="modelName"
        :detail-data="detailData"
        @change="handleWorkflow"
      />
      <!-- workflow 表单 -->
      <WizardForm ref="wizardForm" :model-name="modelName" @changed="getData" />
    </div>
    <br />
    <br />
    <div>
      <div class="filter-container">
        <el-button
          v-if="checkHidden(handle, 'edit')"
          class="filter-item"
          style="margin-left: 10px;width:100px;line-height: 37px;margin-top:19px;"
          type="primary"
          icon="el-icon-edit"
          @click="handleHeadEdit"
        >
          {{ handle.edit.text }}
        </el-button>
      </div>
      <slot name="before" :detailData="detailData" />
      <el-form v-if="debug" label-position="left">
        <el-row>
          <el-col :span="8">
            <el-form-item label="ID">
              <span>{{ detailData.id }}</span>
            </el-form-item>
          </el-col>
          <el-col v-for="col in columns" :key="col.name" :span="8">
            <el-form-item :label="`${col.label}:`">
              <span>{{ detailData[col.name] }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <slot name="after" :detailData="detailData" />
      <!-- <table class="table-1">
        <tr v-for="col in columns" :key="col.name">
          <td class="small">{{ col.label }}:</td>

          <td>{{ detailData[col.name] }}</td>
        </tr>
      </table> -->
    </div>
    <br />
    <br />

    <div v-for="field in childField" :key="field">
      <div class="line" />
      <div class="line" />
      <br />
      <br />
      {{ (child_configs[field] || {}).label }}
      <br />
      <el-button
        v-if="checkCreateHidden(field)"
        class="filter-item"
        style="margin-left: 10px;width:100px;line-height: 40px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate(field)"
      >
        {{ get_create_text(field) }}
      </el-button>
      <br />
      <TableList
        ref="tableList"
        :model-name="modelName"
        :child-field-name="field"
        :list="detailData[`${field}__objects`]"
        @handle-click="handleClick"
      />

      <!-- 表单 :model-name="modelName" @changed="getData" -->
      <FormDialog
        ref="formDialogChild"
        :model-name="modelName"
        :child-field-name="field"
        @changed="getData"
      />
    </div>

    <!-- 表单 :model-name="modelName" @changed="getData" -->
    <FormDialog
      ref="formDialogHeader"
      :model-name="modelName"
      @changed="getData"
    />
  </div>
</template>

<script>
import odoo from '@/odooapi'

import Workflow from '@/selfComponents/Workflow'
import TableList from '@/selfComponents/TableList'
import FormDialog from '@/selfComponents/FormDialog'
import WizardForm from '@/selfComponents/Workflow/WizardForm'

const handle_default = {
  edit: { text: '修改' }
}

export default {
  name: 'DetailPage',
  components: { Workflow, WizardForm, TableList, FormDialog },

  directives: {},
  filters: {},

  props: {
    modelName: { type: String, default: '' },
    childFieldName: { type: null, default: () => [] },
    recId: { type: Number, default: 0 },
    editMethod: { type: String, default: 'write' }

    // 编辑按钮 需要 以参数形式传进来？
  },

  data() {
    return {
      debug: odoo.debug,
      Model: undefined,
      columns: [],
      detailData: {},
      handle: handle_default,
      child_configs: {},

      activeState: { value: 'draft' },
      workflowConfigs: undefined
    }
  },

  computed: {
    childField: function() {
      // return []
      if (typeof this.childFieldName === 'string') {
        return [this.childFieldName]
      } else {
        return Array.isArray(this.childFieldName) ? this.childFieldName : []
      }
    }
  },

  async created() {
    this.Model = odoo.env(this.modelName)

    const {
      workflow,
      detail_columns,
      child_configs,
      handle
    } = this.Model.configs

    this.child_configs = child_configs || {}
    this.columns = detail_columns || []
    this.handle = handle || handle_default

    this.workflowConfigs = workflow

    this.getData()
  },

  methods: {
    checkHidden(handle, type, row) {
      if (handle[type] && handle[type].hidden) {
        const hidden = handle[type].hidden
        const hidden2 =
          typeof hidden === 'function'
            ? hidden({ self: this.Model, rec: row })
            : hidden
        return !hidden2
      } else {
        return true
      }
    },

    checkCreateHidden(field) {
      const handle = this.child_configs[field].handle || {}
      const create = handle.create || {}
      if (create && create.hidden) {
        const hidden = create.hidden
        const hidden2 =
          typeof hidden === 'function' ? hidden({ self: this.Model }) : hidden
        return !hidden2
      } else {
        return true
      }
    },

    get_create_text(field) {
      const handle = this.child_configs[field].handle || {}
      const create = handle.create || {}
      return create.text || '添加'
    },

    async handleWorkflow(active_state) {
      // console.log('xxxx,', active_state)
      // to call  odooo
      if (active_state.value !== 'update') {
        // 有些 workflow 的 action methon，可能会有额外的参数
        // 这些额外的参数, 是特定的页面自己传过来的

        // TBD 2020-1-9
        // 根据 workflow 的 返回值 决定 下一步的动作
        const action = this.workflowConfigs.actions[active_state.value]
        if (action.odoo_type && action.odoo_type === 'action') {
          // action open a form
          // 如打开一个 wizard form 页面
          // 初始化 formItems 的  select 字段的 options
          // console.log('xxxxxx, action,', active_state.value, action)
          await this.Model.env(action.wizard.model).formOptions(
            action.wizard.formItems
          )

          const res = await this.Model.workflow({
            rec: this.detailData,
            next: active_state.value,
            last: active_state.last,

            // 额外的参数
            kwargs: {}
          })

          console.log('xxxxxx, wkf ok ', res, action)
          this.$refs['wizardForm'].handleUpdate(res, {
            actionName: active_state.value,
            detailData: this.detailData
          })
        } else if (action.odoo_type && action.odoo_type === 'new') {
          console.log('xxxxxx, action new', action.method)
          const res = await this.Model[action.method](this.detailData.id)
          console.log('xxxxxx, action new 2 ', res)
          this.$emit('action', {
            detailData: this.detailData,
            action,
            action_data: res
          })

          //
        } else {
          // const res =
          await this.Model.workflow({
            rec: this.detailData,
            next: active_state.value,
            last: active_state.last,

            // 额外的参数
            kwargs: {}
          })

          this.activeState = active_state
          await this.getData()

          // 有些 action 没有返回值

          // if (res) {
          //   this.activeState = active_state
          //   await this.getData()
          // }
        }
      } else {
        // console.log('to update')
        // const method = this.workflowConfigs.actions[active_state.value].method
        // 这个不对
        // this.handleHeadEdit(method)
        this.handleHeadEdit()
      }
    },

    reset_all() {
      this.activeState = { value: 'draft' }
    },

    async getData() {
      const rid = this.$route.query.id || this.recId
      this.detailData = await this.Model.browse_one(rid)

      console.log('xxxxxxx, detail data,', this.detailData)

      if (this.detailData.state) {
        this.activeState = { value: this.detailData.state }
      }

      this.$emit('change', this.detailData)
    },

    handleHeadEdit() {
      // console.log('xxxxxx, handleHeadEdit')
      // 这里 点击事件, 第一个参数 有东西. 所有工作流的 内容， 需要严格测试
      this.$refs['formDialogHeader'].handleUpdate(this.detailData, {
        method: this.editMethod
      })
      // this.$refs['formDialogHeader'].handleUpdate(this.detailData)
    },

    handleCreate(field) {
      const refs = this.$refs['formDialogChild'] || []
      const refs2 = refs.filter(ref => ref.childFieldName === field)

      const ref = refs2.length ? refs2[0] : null
      if (ref) {
        ref.handleCreate(this.detailData.id, this.detailData)
      }
    },

    handleClick(row, { field, handle }) {
      if (handle === 'update') {
        this.handleUpdate(row, field)
      } else if (handle === 'remove') {
        this.handleRemove(row, field)
      }
    },

    handleUpdate(row, field) {
      const refs = this.$refs['formDialogChild'] || []
      const refs2 = refs.filter(ref => ref.childFieldName === field)

      const ref = refs2.length ? refs2[0] : null
      if (ref) {
        ref.handleUpdate(row, { head_id: this.detailData.id })
      }
    },

    handleRemove(row, field) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // eslint-disable-next-line space-before-function-paren
        .then(async () => {
          // this.unlinkpost(row.id)
          const vals = { id: this.detailData.id }
          vals[field] = [[2, row.id]]
          const res = await this.Model.write(vals)

          if (res) {
            this.getData()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
<style scoped>
.line {
  width: 100%;
  height: 1px;
  background: #ccc;
}
table {
  width: 50%;
  background: #fff;
  /* margin: 10px auto; */
  margin-left: 25px;
  border-radius: 8px;
  /* text-align: center; */
}

.table-1 {
  border: 1px solid #ccc;
  font-size: 13px;
  border-collapse: collapse;
  background: #fff;
  border-radius: 8px;
}

.table-1 tr,
.table-1 td {
  border: 1px solid #ccc;
  line-height: 30px;
}
</style>
